/**
 *
 * @param {*} tree 树形数据
 * @param {*} childrenField 树形数据子节点字段名
 * @param {*} flatArray [可选] 结果集
 * @returns 树形数据所有子节点数组
 */
export function getTreeChildren(
  tree,
  childrenField = 'children',
  flatArray = []
) {
  if (!tree) {
    return flatArray
  }
  if (!tree[childrenField]) {
    return flatArray.push(tree)
  }
  tree[childrenField].forEach(item => {
    if (item[childrenField] && item[childrenField].length > 0) {
      getTreeChildren(item, childrenField, flatArray)
    } else {
      flatArray.push(item)
    }
  })
  return flatArray
}

const outRootLink = [
  
]
const outRootLinkMenus = outRootLink.reduce((data, item, index) => {
  if (!item) {
    return data
  }

    const flatChildren = getTreeChildren(item)

    data.push({
      ...item
      // children: flatChildren
    })
  
  return data
}, [])
console.log(outRootLinkMenus, 'mmmmm');


/**
 * 树结构数组重构：将组织树后台返回树结构字段内容转换为antd-Tree组件所需要的字段内容
 *    不改变原数据结构，将原先多层树结构中的name替换为title, array替换为children
 * @params :
 *    [ 
        {name:'张三',array:[]}, 
        {name:'张三',array:[{name:'李四',array:[]}] },
        {name:'张三',array:[{name:'李四',array:[{name:'王五',array:[]}]}]} 
      ]
 * @returns :
      [ 
        {title:'张三',children:[]},
        {title:'张三',children:[{title:'李四',children:[]}] },
        {title:'张三',children:[{title:'李四',children:[{title:'王五',children:[]}]}]} 
      ] 
  * @actions : changeTreeArr(params) === returns
 */
export function changeTreeArr(treeData) {
  function loopTreeArr(item) {
    const haveChildren = Array.isArray(item.array) && item.array.length > 0;
    return {
      title: item.name,
      children: haveChildren ? item.array.map(i => loopTreeArr(i)) : [],
    }
  }
  return treeData.map(item => loopTreeArr(item))
}
            
/**
 * 树结构数组拍平
 *    在原多维数组基础上追加含有children的项, 得到结果遍历后收集项目中children长度大于0项的key集合数组
 * @params :
 *    [ 
        {title:'张三',children:[],key:1},
        {title:'张三',children:[{title:'李四',children:[],key:3}],key:2},
        {title:'张三',children:[{title:'李四',children:[{title:'王五',children:[],key:6}],key:5}],key:4} 
      ] 
  * @handle :
      [ 
        {title:'张三',children:[],key:1},
        {title:'张三',children:[{title:'李四',children:[],key:3}}],key:2},
        {title:'李四',children:[],key:3},
        {title:'张三',children:[{title:'李四',children:[{title:'王五',children:[],key:6}],key:5}],key:4},
        {title:'李四',children:[{title:'王五',children:[],key:6}],key:5},
        {title:'王五',children:[],key:6} 
      ] 
  * @returns : [2, 4, 5]
  * @actions : expandKeyArr(params) === returns
*/
export function getExpandKey(arr){
  function flatArr(arr,brr){
    arr.forEach(item => {
      brr.push(item)
      if(item.children){
        flatArr(item.children,brr)
      }  
    });
    return brr
  }
  
  let result = flatArr(arr,[]), expandKeyArr = []
  result.forEach(i=>{
    if(Array.isArray(i.children) && i.children.length > 0){
      expandKeyArr.push(i.key)
    }
  })
  return expandKeyArr
}